<?php

use console\db\Migration;
use yii\db\Query;
use yii\db\Expression;
use yii\helpers\ArrayHelper;

/**
 * 清理非法IP信息
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300000_000006_t_user_meta_filter_ip extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%user_meta}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $column = 'temp_ip';
        $query = (new Query())->from($this->tableName)->select([
            'id',
        ])->where([
            'and',
            ['IS NOT', $column, null],
            ['!=', $column, ''],
            new Expression('ISNULL(INET_ATON(' . $column . '))')
        ]);
        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        if (empty($rows)) {
            return;
        }
        $ids = ArrayHelper::getColumn($rows, 'id');
        $migration->db->createCommand()->update($migration->tableName, [
            'temp_ip' => ''
        ], ['id' => $ids])->execute();
    }

}
